import json
import os
import shutil
import time
import zipfile

import requests

import api
from DBAction import DBAction


def getbqb():
    # api.start_schedule()
    db = DBAction('pocket48')
    #  按照粉丝数获得member_list
    result = db.data_inquiry_all("SELECT m.memberid,r.roomid FROM member m left join room r on m.memberid=r.memberid "
                                 "where m.fan_num < 7410 and r.roomid is not null order by m.fan_num desc")

    url = 'https://pocketapi.48.cn/app-activity/api/activity/emoti/v1/vote/list'
    pagecount = 0
    starname = ''
    # rank = 0
    for data in result:
        id = data[0]
        time.sleep(20)
        while True:
            params = {"lastPageParam": pagecount, "layout": 0, "starId": id}
            response = api.post(url, params, header=api.get_live_header())
            print(url, response)
            if response['status'] == 200:
                if pagecount == 0:
                    starname = response['content']['starEmotiVoteInfo']['starName']
                    print(starname)

                l = response['content']['emotiDatas']
                for data in l:
                    # print(data['emotiPath'])
                    # data = json.loads(data)
                    path = data['emotiPath']
                    imgurl = f'https://source.48.cn{path}'
                    date_str = ''
                    # image_filename = str(rank).zfill(4) + "_" + path.split('/')[2]
                    if path == '':
                        continue
                    image_filename = path.split('/').pop()
                    # 创建的目录
                    savepath = f"D:/pocket48_bqb/{starname}"
                    img_name = f'{savepath}/{image_filename}'
                    # print(img_name)

                    if not os.path.exists(savepath):
                        os.makedirs(savepath)

                    if not os.path.exists(img_name):
                        html = requests.get(imgurl, verify=False)
                        with open(img_name, 'wb') as f:
                            f.write(html.content)
                        f.close()
                    api.wait_random_time()
                    # rank += 1
                if pagecount != 0:
                    if response['content']['isOver']:
                        # rank = 0
                        pagecount = 0
                        print('normal end')
                        break

                pagecount = response['content']['nextId']
                time.sleep(15)
            else:
                # rank = 0
                pagecount = 0
                print('end')
                break


def get_team_members(team):
    db = DBAction('pocket48')
    #  按照粉丝数获得member_list
    result = db.data_inquiry_all(f"SELECT m.name FROM member m where m.team='{team}' order by m.fan_num desc")
    names = []
    for data in result:
        names.append(data[0])
    return names


def split_by_team():
    teamlist = ['荣誉毕业生', 'SII', 'NII', 'HII', 'X', 'G', 'NIII', 'Z', 'BEJ', 'IDFT']
    root = r'D:\pocket48_bqb'
    for team in teamlist:
        names = get_team_members(team)
        teamfolder = os.path.join(root, team)
        os.makedirs(teamfolder, exist_ok=True)
        for name in names:
            src = os.path.join(root, name)
            if os.path.exists(src):
                shutil.move(src, teamfolder)


def zipDir():
    """
    压缩文件夹
    """
    root = r'D:\pocket48_bqb'
    dirs = os.listdir(root)
    for dir in dirs:
        dir_full_path = os.path.join(root, dir)
        zip = zipfile.ZipFile(dir_full_path + '.zip', "w", zipfile.ZIP_DEFLATED)
        for path, dirnames, filenames in os.walk(dir_full_path):
            for filename in filenames:
                # arcname是打开zip包的路径，需要去掉root，以队名为首级目录
                arcname = os.path.join(path.replace(root, ''), filename)
                zip.write(os.path.join(path, filename), arcname)
        zip.close()


if __name__ == '__main__':
    # split_by_team()
    zipDir()

"""
POST https://pocketapi.48.cn/app-activity/api/activity/emoti/v1/vote/list HTTP/1.1
Host: pocketapi.48.cn
Content-Type: application/json; charset=UTF-8
Origin: https://h5.48.cn
Accept-Language: zh-cn
Accept-Encoding: br, gzip, deflate
Connection: keep-alive
Accept: */*
User-Agent: Mozilla/5.0 (iPad; CPU OS 12_5_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148
Referer: https://h5.48.cn/2021apppage/labourDayb/minfo.html?sid=677404
token: 63Z8CHGxN3wyisUx+6bfk137zKqHbuNzUOQg2p4Ksazq3Z0+4xLOnia0u2FJyvZNGNcmxfAiBL62NhMK9g65v0VGTWbQPsYbN9qPAvoztsVIuMBOgBQeQcym6d2QIozS
Content-Length: 48

{"lastPageParam":0,"layout":2,"starId":"677404"}
"""
